//
//  ShareCustom.m
//  ChiChiFan
//
//  Created by leidian on 15/9/13.
//  Copyright (c) 2015年 mumuxinxinCompany. All rights reserved.
//

#import "ShareCustom.h"


//设备物理大小
#define kScreenWidth   [UIScreen mainScreen].bounds.size.width
#define kScreenHeight  [UIScreen mainScreen].bounds.size.height
#define SYSTEM_VERSION   [[UIDevice currentDevice].systemVersion floatValue]
//屏幕宽度相对iPhone6屏幕宽度的比例
#define KWidth_Scale    [UIScreen mainScreen].bounds.size.width/375.0f

#define kHRGBA(rgbValue, alphaValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:alphaValue]

#define kHRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]


static id _publishContent;//类方法中的全局变量这样用（类型前面加static）
static UITapGestureRecognizer *recognizerTap;
static UIView *shareView;
static UIView *blackView;

@implementation ShareCustom

/*
 自定义的分享类，使用的是类方法，其他地方只要 构造分享内容publishContent就行了
 */

+ (void)shareWithContent:(NSString *)content
                          pngImageUrlString:(NSString *)pngImageUrlString
                                      title:(NSString *)title
                                        url:(NSString *)callBackUrlString
                                     sender:(id) sender;
{
    //构造分享内容
    id<ISSContent> publishContent = [ShareSDK content:[NSString stringWithFormat:@"%@\r\n%@", content, callBackUrlString]
                                       defaultContent:@""
                                                image:[ShareSDK imageWithUrl:pngImageUrlString]
                                                title:title
                                                  url:callBackUrlString
                                          description:NSLocalizedString(@"TEXT_TEST_MSG", @"分享")
                                            mediaType:SSPublishContentMediaTypeNews];
    
    //定制QQ空间信息
    [publishContent addQQSpaceUnitWithTitle:title
                                        url:callBackUrlString
                                       site:nil
                                    fromUrl:nil
                                    comment:nil
                                    summary:content
                                      image:[ShareSDK imageWithUrl:pngImageUrlString]
                                       type:[NSNumber numberWithInt:4]
                                    playUrl:nil
                                       nswb:nil];
    
    //定制微信好友信息
    [publishContent addWeixinSessionUnitWithType:[NSNumber numberWithInt:SSPublishContentMediaTypeNews]
                                         content:content
                                           title:title
                                             url:callBackUrlString
                                      thumbImage:nil
                                           image:[ShareSDK imageWithUrl:pngImageUrlString]
                                    musicFileUrl:nil
                                         extInfo:nil
                                        fileData:nil
                                    emoticonData:nil];
    
    //定制微信朋友圈信息
    [publishContent addWeixinTimelineUnitWithType:[NSNumber numberWithInteger:SSPublishContentMediaTypeNews]
                                          content:content
                                            title:title
                                              url:callBackUrlString
                                       thumbImage:nil
                                            image:[ShareSDK imageWithUrl:pngImageUrlString]
                                     musicFileUrl:nil
                                          extInfo:nil
                                         fileData:nil
                                     emoticonData:nil];
    
    //定制QQ分享信息
    [publishContent addQQUnitWithType:[NSNumber numberWithInteger:SSPublishContentMediaTypeNews]
                              content:content
                                title:title
                                  url:callBackUrlString
                                image:[ShareSDK imageWithUrl:pngImageUrlString]];
    
    //定制短信信息
    NSString *message = nil;
    if (content.length > 121) {
        message = [content substringToIndex:120];
    }
    else
    {
        message = content;
    }
    [publishContent addSMSUnitWithContent:[NSString stringWithFormat:@"%@..更多看这里:\r\n%@", message, callBackUrlString]];
    
    [self shareWithContent:publishContent];
}

+(void)shareWithContent:(id)publishContent/*只需要在分享按钮事件中 构建好分享内容publishContent传过来就好了*/
{
    _publishContent = publishContent;
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    
    blackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    blackView.backgroundColor = kHRGBA(0x000000, 0.85f);
    blackView.tag = 440;
    [window addSubview:blackView];
    
    shareView = [[UIView alloc] initWithFrame:CGRectMake((kScreenWidth-300*KWidth_Scale)/2.0f, (kScreenHeight-270*KWidth_Scale)/2.0f, 300*KWidth_Scale, 270*KWidth_Scale)];
    shareView.backgroundColor = kHRGB(0xf6f6f6);
    shareView.tag = 441;
    [window addSubview:shareView];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(shareView.frame), 45*KWidth_Scale)];
    titleLabel.text = @"分享到";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [UIFont systemFontOfSize:15*KWidth_Scale];
    titleLabel.textColor = kHRGB(0x2a2a2a);
    titleLabel.backgroundColor = [UIColor clearColor];
    [shareView addSubview:titleLabel];
    
    /**图片命名见Commons-Thirdparty-ShareSdk-core-Resource.bundle-Icon_7*/
    NSArray *btnImages = @[@"Share_Wechat", @"Share_WechatTimeline", @"Share_QQ", @"Share_QZone", @"Share_SinaWeibo", @"Share_Mail", @"Share_SMS", @"Share_Copy"];
    NSArray *btnTitles = @[@"微信好友", @"朋友圈", @"QQ好友", @"QQ空间", @"新浪微博", @"邮件", @"短信" , @"复制"  ];
    for (NSInteger i=0; i<8; i++) {
        CGFloat top = 0.0f;
        if (i<4) {
            top = 30*KWidth_Scale;
            
        }else{
            top = 120*KWidth_Scale;
        }
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10*KWidth_Scale+(i%4)*70*KWidth_Scale, CGRectGetMaxY(titleLabel.frame)+top, 70*KWidth_Scale, 70*KWidth_Scale)];
        [button setImage:[UIImage imageNamed:btnImages[i]] forState:UIControlStateNormal];
        [button setTitle:btnTitles[i] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:11*KWidth_Scale];
        button.titleLabel.textAlignment = NSTextAlignmentCenter;
        [button setTitleColor:kHRGB(0x2a2a2a) forState:UIControlStateNormal];
        
        [button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
        [button setContentVerticalAlignment:UIControlContentVerticalAlignmentTop];
        [button setImageEdgeInsets:UIEdgeInsetsMake(0, 15*KWidth_Scale, 30*KWidth_Scale, 15*KWidth_Scale)];
        if (SYSTEM_VERSION >= 8.0f) {
            [button setTitleEdgeInsets:UIEdgeInsetsMake(45*KWidth_Scale, -66*KWidth_Scale, 5*KWidth_Scale, 0)];
        }else{
            [button setTitleEdgeInsets:UIEdgeInsetsMake(45*KWidth_Scale, -90*KWidth_Scale, 5*KWidth_Scale, 0)];
        }
        
        button.tag = 331+i;
        [button addTarget:self action:@selector(shareBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [shareView addSubview:button];
    }
    
//    UIButton *cancleBtn = [[UIButton alloc] initWithFrame:CGRectMake((CGRectGetWidth(shareView.frame)-40*KWidth_Scale)/2.0f, CGRectGetHeight(shareView.frame)-40*KWidth_Scale-18*KWidth_Scale, 40*KWidth_Scale, 40*KWidth_Scale)];
//    [cancleBtn setBackgroundImage:[UIImage imageNamed:@"IOS-取消@2x.png"] forState:UIControlStateNormal];
//    cancleBtn.tag = 339;
//    [cancleBtn addTarget:self action:@selector(shareBtnClick:) forControlEvents:UIControlEventTouchUpInside];
//    [shareView addSubview:cancleBtn];
    
    recognizerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapBehind:)];
    [recognizerTap setNumberOfTapsRequired:1];
    recognizerTap.cancelsTouchesInView = NO;
    [blackView addGestureRecognizer:recognizerTap];
    
    //为了弹窗不那么生硬，这里加了个简单的动画
    shareView.transform = CGAffineTransformMakeScale(1/300.0f, 1/270.0f);
    blackView.alpha = 0;
    [UIView animateWithDuration:0.35f animations:^{
        shareView.transform = CGAffineTransformMakeScale(1, 1);
        blackView.alpha = 1;
    } completion:^(BOOL finished) {
        
    }];
    
}

+ (void)handleTapBehind:(UITapGestureRecognizer *)sender
{

    if (sender.state == UIGestureRecognizerStateEnded){
        CGPoint location = [sender locationInView:nil];
        
        if (![shareView pointInside:[shareView convertPoint:location fromView:blackView] withEvent:nil]){
            //为了弹窗不那么生硬，这里加了个简单的动画
            shareView.transform = CGAffineTransformMakeScale(1, 1);
            [UIView animateWithDuration:0.35f animations:^{
                shareView.transform = CGAffineTransformMakeScale(1/300.0f, 1/270.0f);
                blackView.alpha = 0;
            } completion:^(BOOL finished) {
                
                [shareView removeFromSuperview];
                [blackView removeFromSuperview];
            }];
            
            [[UIApplication sharedApplication].keyWindow removeGestureRecognizer:sender];
//            [self removeFromSuperview];
        }
    }
    //    [self.window removeGestureRecognizer:sender];
}

+(void)shareBtnClick:(UIButton *)btn
{
    NSLog(@"[ShareSDK version]=========%@",[ShareSDK version]);
    NSLog(@"btn.tag===========%ld",btn.tag);
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIView *blackView = [window viewWithTag:440];
    UIView *shareView = [window viewWithTag:441];
    
    //为了弹窗不那么生硬，这里加了个简单的动画
    shareView.transform = CGAffineTransformMakeScale(1, 1);
    [UIView animateWithDuration:0.35f animations:^{
        shareView.transform = CGAffineTransformMakeScale(1/300.0f, 1/270.0f);
        blackView.alpha = 0;
    } completion:^(BOOL finished) {
        
        [shareView removeFromSuperview];
        [blackView removeFromSuperview];
    }];
    
    int shareType = 0;
    id publishContent = _publishContent;
    switch (btn.tag) {
        case 331:
        {
            shareType = ShareTypeWeixiSession;
        }
            break;
            
        case 332:
        {
            shareType = ShareTypeWeixiTimeline;
        }
            break;
            
        case 333:
        {
            shareType = ShareTypeQQ;
        }
            break;
        case 334:
        {
            shareType = ShareTypeQQSpace;
        }
            break;
            
        case 335:
        {
            shareType = ShareTypeSinaWeibo;
        }
            break;
            
        case 336:
        {
            shareType = ShareTypeMail;
        }
            break;
            
        case 337:
        {
            shareType = ShareTypeSMS;
        }
            break;
            
        case 338:
        {
            shareType = ShareTypeCopy;
        }
            break;
            
        case 339:
        {
            
        }
            break;
            
        default:
            break;
    }
    /*
     调用shareSDK的无UI分享类型，
     链接地址：http://bbs.mob.com/forum.php?mod=viewthread&tid=110&extra=page%3D1%26filter%3Dtypeid%26typeid%3D34
     */
    [ShareSDK showShareViewWithType:shareType container:nil content:publishContent statusBarTips:YES authOptions:nil shareOptions:nil result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
        if (state == SSResponseStateSuccess)
        {
            //            NSLog(NSLocalizedString(@"TEXT_ShARE_SUC", @"分享成功"));
        }
        else if (state == SSResponseStateFail)
        {
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"" message:[error errorDescription] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            NSLog(@"======%@--------", error);
            [alert show];
            //            NSLog(NSLocalizedString(@"TEXT_ShARE_FAI", @"分享失败,错误码:%d,错误描述:%@"), [error errorCode], [error errorDescription]);
        }
    }];
}


@end
